<?php

namespace App\Http\Controllers;

use App\Http\Requests\PhoneRequest;
use App\Http\Requests\UserRequest;
use App\Models\Phone;
use App\Models\PhoneSetting;
use App\Models\Role;
use App\Models\User;
use App\Services\PlivoService;
use App\Services\TwilioService;
use App\Transformers\UserTransformer;
use App\Transformers\UserImportTransformer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use App\Transformers\FsUserTransformer;
use App\Imports\FsUserImport;
use Excel;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;

class UserController extends CallBaseController
{
    protected $settingId;
    protected $plivoService;
    public function __construct(PlivoService $plivoService)
    {
        parent::__construct();

        $this->settingId = DB::table('phone_settings')->where('status',1)->first()->id;

        $this->plivoService = $plivoService;
    }

    /**
     * @api {get} /api/users?include=phones&search=XXX&page=1&limit=2 用户列表
     * @apiGroup User
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {String} search  搜索条件
     * @apiParam {int} page   当前页数
     * @apiParam {int} limit  返回总条数
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
            {
                "data": [
                    {
                        "id": 1,
                        "name": "admin",
                        "section_id": "",
                        "branch_id": "",
                        "role_id": "",
                        "status": 1,
                        "created_at": "",
                        "updated_at": "2018-12-14 15:05:24"
                    }
                ],
                "meta": {
                    "pagination": {
                        "total": 42,
                        "count": 1,
                        "per_page": 1,
                        "current_page": 1,
                        "total_pages": 42,
                        "links": {
                        "previous": null,
                        "next": "http://dianyun2.com/api/users?page=2"
                      }
                    }
                }
            }
     */
    public function index(User $user, Role $role, Request $request){
        $setting_id = $this->settingId;
        $builder = User::query();
        $res = $role->getIdAndNameToArray();

        if ($search = $request->input('search', '')){
            $like = '%'.$search.'%';
            $builder->where('name', 'like', $like);
        }
        //如果没有查看所有人的权限
        if(!Auth::user()->hasRole('超级管理员')){
            $branch_id = Auth::user()->branch_id;
            $section_id = Auth::user()->section_id;
            if($branch_id){
                $role_ids = $this->roleIds($branch_id);
                $users = $builder->whereIn('role_id',$role_ids)->paginate($request->get('limit',10));
            }elseif($section_id){
                $section_id = Auth::user()->section_id;
                $role_ids = $this->roleIds($section_id);
                $users = $builder->whereIn('role_id',$role_ids)->paginate($request->get('limit',10));
            }else{
                return $this->response->item(Auth::user(), new UserTransformer($res,$setting_id));
            }
            return $this->response->paginator($users, new UserTransformer($res,$setting_id));
        }else{
            $users = $builder->paginate($request->get('limit',10));

            return $this->response->paginator($users, new UserTransformer($res,$setting_id));
        }
    }

    /**
     * @api {get} /api/users/index?page=1&limit=2 用户会员列表
     * @apiGroup User
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {String} search  搜索条件
     * @apiParam {int} page   当前页数
     * @apiParam {int} limit  返回总条数
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     *       {
     *           "data": [
     *               {
     *                   "id": 1,
     *                   "name": "admin",
     *                   "section_id": "",
     *                   "branch_id": "",
     *                   "role_id": "",
     *                   "fs_user_count": 2,
     *                   "created_at": "",
     *                   "updated_at": "2018-12-14 15:05:24"
     *               }
     *           ],
     *               "meta": {
     *                   "pagination": {
     *                       "total": 42,
     *                       "count": 1,
     *                       "per_page": 1,
     *                       "current_page": 1,
     *                       "total_pages": 42,
     *                       "links": {
     *                       "previous": null,
     *                       "next": "http://dianyun2.com/api/users?page=2"
     *                   }
     *               }
     *           }
     *       }
     */
    public function userIndex(User $user, Role $role, Request $request){
        $setting_id = $this->settingId;
        $builder = User::query();
        $res = $role->getIdAndNameToArray();

        $users = $builder->where('status',1)->paginate($request->get('limit',10));

        return $this->response->paginator($users, new UserImportTransformer($res));
    }

    /**
     * @api {get} /api/users/show?page=1&limit=2 用户会员详情
     * @apiGroup User
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} user_id   后台用户id
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     *       {
     *           "data": [
     *               {
     *                  "id": 182833,
     *                   "username": "wq950416",
     *                   "agent": "denci888",
     *                   "register_time": "2018-10-19 08:53:53",
     *                   "balance": "0.44",
     *                   "last_login_time": "2018-12-15 07:19:15",
     *                   "last_charge_time": "2018-12-05 09:12:08",
     *                   "last_refund_time": "2018-12-05 09:31:00",
     *                   "ip": "39.188.128.22",
     *                   "status": "启用",
     *                   "lev": "B◆单笔1000",
     *                   "true_name": "李笔记",
     *                   "true_id": null,
     *                   "phone_num": "+18122213998",
     *                   "qq": null,
     *                   "mail": null,
     *                   "province": "陕西省",
     *                   "city": "礼泉县",
     *                   "bank_name": "中国邮政",
     *                   "bank_num": null,
     *                   "remark": null,
     *                   "site_id": 1001,
     *                   "deposit_count": "19.00",
     *                   "deposit_max": "1000.00",
     *                   "deposit_total": "4330.00",
     *                   "withdrawal_count": "5.00",
     *                   "withdrawal_total": "7000.00",
     *                   "multiple": "0.6186",
     *                   "profit": null,
     *                   "call_status": ""
     *               }
     *           ],
     *               "meta": {
     *                   "pagination": {
     *                       "total": 42,
     *                       "count": 1,
     *                       "per_page": 1,
     *                       "current_page": 1,
     *                       "total_pages": 42,
     *                       "links": {
     *                       "previous": null,
     *                       "next": "http://dianyun2.com/api/users?page=2"
     *                   }
     *               }
     *           }
     *       }
     */
    public function userFsUserShow(Request $request){
        $data = $request->validate([
            'user_id'=>'required|exists:mysql.users,id,status,1,deleted_at,NULL',
        ]);
        $fsUsers = User::find($data['user_id'])->fsUsers()->distinct()->paginate($request->get('limit',10));
        return $this->response->paginator($fsUsers, new FsUserTransformer());
    }
    /**
     * @api {post} /api/users 用户添加
     * @apiGroup User
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {String} name  名称（必传参数）
     * @apiParam {int} section_id  部门id
     * @apiParam {int} branch_id  部门分支id
     * @apiParam {int} role_id  岗位id
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 201 OK
     */
    public function store(UserRequest $request, User $user){
        $user->fill($request->all());
        $user->password = bcrypt(env('RESET_PASSWORD', '000000'));
        $user->save();

        return $this->response->created();
    }

    /**
     * @api {post} /api/users/:user 用户展示
     * @apiGroup User
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} user 用户id(url中传入，必传参数)
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     *       {
     *           "id": 3,
     *           "name": "ceshi",
     *           "section_id": "运维",
     *           "branch_id": "运维分支",
     *           "role_id": "运维角色",
     *           "status": 1,
     *           "created_at": "2018-12-14 11:27:46",
     *           "updated_at": "2018-12-14 11:27:46"
     *       }
     */
    public function show(User $user, Role $role){
      $res = $role->getIdAndNameToArray();
      return $this->response->item($user,new UserTransformer($res));
    }

    /**
     * @api {delete} /api/users/:user 用户删除和批量删除
     * @apiGroup User
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} user 用户id(url中传入，必传参数)
     * @apiParam {array} ids api/users/batch/delete
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 204 OK
     */
    public function destroy(User $user, Request $request){
        $setting_id = $this->settingId;
        if($request->method() == 'DELETE'){
            if($user->phones()->where('phone_setting_id',$setting_id)->first()){
                return response()->json(['error' => '请先解绑手机号'], 422);
            }
            $user->delete();
        }else{
            $validatedData = $request->validate([
                'ids' => 'array',
                'ids.*'=> 'exists:users,id'
            ],[],[
                'ids'=>'用户',
                'ids.*'=>'用户'

            ]);

            if($validatedData['ids']){
                User::destroy($validatedData['ids']);
            }
        }
        return $this->response->noContent();
    }

    /**
     * @api {patch} /api/users/:user 用户修改（修改，重置，屏蔽）
     * @apiGroup User
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} user 用户id(url中传入，必传参数)
     * @apiParam {string} 1name 名称
     * @apiParam {int} 2section_id 部门id
     * @apiParam {int} 3branch_id 部门分支id
     * @apiParam {int} 4role_id 岗位id
     * @apiParam {int} 5reset 密码重置 1
     * @apiParam {int} 6status 禁用 0或者1
     * @apiParam {string} desc 修改:1234;密码重置:5;屏蔽:6
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     *       {
     *             "message": "修改成功"
     *       }
     */
    public function update(UserRequest $request, User $user){
        $input = $request->all();
        if($request->reset){
            $user->password = bcrypt(env('RESET_PASSWORD', '000000'));
        }elseif (isset($request->status)){
            $user->status = $request->status;
        }else{
            if(!isset($request->branch_id)){
                $input['branch_id'] = null;
            }
            $user->syncRoles($request->role_id);
            $user->fill($input);
        }
        $user->save();
        return response()->json(['message' => '修改成功']);
    }

    /**
     * @api {post} /api/users/:user/bind 手机绑定
     * @apiGroup Phone
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} user 用户id(url中传入，必传参数)
     * @apiParam {int} id 手机id
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     *       {
     *             "message": "绑定成功"
     *       }
     */
    public function bindPhone(PhoneRequest $request , User $user, TwilioService $twilioService){
        $setting_id = $this->settingId;
        //用户提交绑定手机号
        $phone = Phone::find($request->id);
        if(!$phone){
            return response()->json(['error' => '手机不存在'], 422);
        }
        //绑定手机不是当前配置
        if($phone->phone_setting_id != $setting_id || $phone->user_id){
            return response()->json(['error' => '手机绑定数据错误'], 422);
        }
        //这个用户已经有绑定
        $user_bind = $user->phones()->where('phone_setting_id',$setting_id)->first();

        if($user_bind){
            return response()->json(['error' => '请先解除绑定'], 422);
        }
        $phoneSetting = PhoneSetting::find($setting_id);
        if($phoneSetting->type == 'twilio'){
            \DB::transaction(function () use ($twilioService, $request, $user, $phone) {
                $phone->user_id = $user->id;
                $phone->save();
                if(!$phone->apps){
                    //给用户注册APPSID
                    $appsid = $twilioService->createSid($phone->phone_number);
                    $phone->apps = $appsid;
                    $phone->save();
                }
            });
        }elseif ($phoneSetting->type == 'plivo'){
            //创建Plivo的应用
            $app = $this->plivoService->createApp();
            //手机绑定这个应用
            if($app){
                $res = $this->plivoService->numberUpdate($phone->phone_number,$app->appId);
                //创建端点绑定应用
                $endpoint = $this->plivoService->createEndpoint($app->appId);
            }
            if($app && $res && $endpoint){
                $phone->user_id = $user->id;
                $phone->apps = $app->appId;
                $phone->username = $endpoint['username'];
                $phone->password = $endpoint['password'];
                $phone->save();
            }elseif ($app && $endpoint){
                //删除App
                $this->plivoService->deleteApp($app->app_id);
                $this->plivoService->deleteEndpoint($endpoint['endpoint_id']);
                return response()->json(['message' => '绑定失败']);
            }elseif ($endpoint){
                //删除端点
                $this->plivoService->deleteEndpoint($endpoint['endpoint_id']);
                return response()->json(['message' => '绑定失败']);
            }else{
                //删除App
                $this->plivoService->deleteApp($app->app_id);
                return response()->json(['message' => '绑定失败']);
            }
        }elseif ($phoneSetting->type == 'sip'){
            $phone->user_id = $user->id;
            $phone->save();
        }
        return response()->json(['message' => '绑定成功']);
    }

    /**
     * @api {post} /api/users/:user/unbind 手机解绑
     * @apiGroup Phone
     *
     * @apiHeader {String} Authorization Bearer+空格+access_token [必填]
     * @apiHeader {String} Accept application/vnd.operationsystem.v1+json [必填]
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} user 用户id(url中传入，必传参数)
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     *       {
     *             "message": "解绑成功"
     *       }
     */
    public function unbindPhone(User $user, TwilioService $twilioService){
        $setting_id = $this->settingId;
        $phoneSetting = PhoneSetting::find($setting_id);
        $bind_phone = $user->phones()->where('phone_setting_id',$this->settingId)->first();

        if($phoneSetting->type == 'twilio'){
            if(empty($bind_phone->user_id) || empty($bind_phone->apps)){
                return response()->json(['error' => '解绑数据有误'], 422);
            }
            //删除对应APPSID
            $twilioService->deleteSid($bind_phone->apps);

        }elseif ($phoneSetting->type == 'plivo'){
            if(empty($bind_phone->user_id) || empty($bind_phone->apps)){
                return response()->json(['error' => '解绑数据有误'], 422);
            }
            //删除App
            $this->plivoService->deleteApp($bind_phone->apps);
        }elseif ($phoneSetting->type == 'sip'){
            //不用处理
        }

        $bind_phone->user_id = null;
        $bind_phone->apps = null;
//        $bind_phone->username = null;
//        $bind_phone->password = null;
        $bind_phone->save();

        return response()->json(['message' => '解绑成功']);
    }

    /**
     * @api {post} /api/users/import?token=access_token 用户会员导入
     * @apiGroup User
     *
     * @apiHeader {String} Content-Type application/json [必填]
     *
     * @apiParam {int} user_id 用户id
     * @apiParam {file} excel 文件
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *       HTTP/1.1 200 OK
     *       {
     *             "message": "导入成功"
     *       }
     */
    public function import(Request $request){
        $data = $request->validate([
            'user_id'=>'required|exists:users,id',
        ]);
        Excel::import(new FsUserImport($data['user_id']), $request->file('excel'));
        return response()->json(['message' => '导入成功']);
    }

    /**
     * 获取所有is_role为true的角色
     * @param $parent_id 要查询的后代所有节点
     */
    public function roleIds($parent_id){
        $roles = Role::all()->toArray();
        $role_data = getTree($roles, $parent_id);

        foreach ($role_data as $v){
            if($v['is_role']== true){
                $roles_ids[] = $v['id'];
            }
        }
        return $roles_ids;
    }
}
